const redisClient = require('../../libs/Redis/redisClient').client;
const Hgetall = require('../../libs/Redis/Hgetall');
const _ = require('underscore');
const conn = require('../../../server/libs/DB/meter/conn');
//const checkThreshold = require('./checkThreshold').checkThreshold;
const moment = require('moment');

async function pushWeatherData(meter) {
    try {
        let deviceNo = meter.deviceNo;//接受到的天气数据
        let data = JSON.parse(meter.data);
        data['currentTime'] = moment().format('YYYY-MM-DD HH:mm:ss');//定义当前数据时间
        let meterData = _.omit(data, 'meterAddr');//去掉表地址多余的字段
        let currentDate = moment(data['currentTime']).format('YYYY-MM-DD');//定义数据日期
        let meterKeyId = `river-course-w-${deviceNo}-${currentDate}`;//存储的数据ID
        let dataObjStr = JSON.stringify(meterData);//转化为字符串以便存入redis
        let redisKey = 'river_course_' + deviceNo + '_weather_threshold';//天气阈值读取的key
        let threshold = await Hgetall(redisKey);//从redis中读取阈值。
        if (threshold.thresholdObj) {
            let alarmSign = false;
            let thresholdObj = JSON.parse(threshold.thresholdObj);
            let alarmDataObj = {};
            const dailyRainfallAccumulationMax = parseFloat(thresholdObj.dailyRainfallAccumulationMax);
            const intervalRainfallAccumulationMax = parseFloat(thresholdObj.intervalRainfallAccumulationMax);
            if (dailyRainfallAccumulationMax && meterData.dailyRainfallAccumulation > dailyRainfallAccumulationMax) {
                alarmSign = true;
                alarmDataObj['dailyRainfallAccumulationMax'] = dailyRainfallAccumulationMax;
                alarmDataObj['dailyRainfallAccumulation'] = meterData.dailyRainfallAccumulation;
            };
            if (intervalRainfallAccumulationMax && meterData.intervalRainfallAccumulation > intervalRainfallAccumulationMax) {
                alarmSign = true;
                alarmDataObj['intervalRainfallAccumulationMax'] = intervalRainfallAccumulationMax;
                alarmDataObj['intervalRainfallAccumulation'] = meterData.intervalRainfallAccumulation;
            };
            if (alarmSign) {
                await conn('insert into alarm_record set ? ', [{
                    alarm_date: meterData.currentTime,
                    device_no: deviceNo,
                    alarm_type: 2,
                    alarm_data_obj: JSON.stringify(alarmDataObj)
                }]);
            }
        }

        redisClient.rpush(meterKeyId, dataObjStr, redisClient.print);
        if (threshold) { };
    } catch (e) {
        console.log(e);
    }
}

exports.pushWeatherData = pushWeatherData;